<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 17/4/12
 * Time: 17:43
 */
class Project_user_model extends BaseModel {



    function __construct()
    {
        parent::__construct(Db_model::TABLE_PROJECT_USER);
    }


    /**
     * 获取用户参与的项目
     * @param $user_id
     * @return mixed
     */
    public function get_user_projects($user_id) {

        return $this->db->select(Db_model::TABLE_PROJECT . ".*, ".Db_model::TABLE_USER . ".username, ". Db_model::TABLE_PROJECT_USER . ".role as project_role")
            ->from(Db_model::TABLE_PROJECT_USER)
            ->join(Db_model::TABLE_PROJECT, Db_model::TABLE_PROJECT.'.id='.Db_model::TABLE_PROJECT_USER.'.pid')
            ->join(Db_model::TABLE_USER, Db_model::TABLE_PROJECT.'.owner_id='.Db_model::TABLE_USER.'.id')
            ->order_by(Db_model::TABLE_PROJECT . ".createtime", "DESC")
            ->where(Db_model::TABLE_PROJECT_USER. ".uid", $user_id)
            ->where(Db_model::TABLE_PROJECT. ".is_deleted", 0)
            ->get()->result_array();
    }

    /**
     * 获取用户创建的项目
     * @param $owner_id
     * @return mixed
     */
    public function get_projects_by_owner_id($owner_id) {
           return $this->db->select(Db_model::TABLE_PROJECT . ".*, ".Db_model::TABLE_USER . ".username " )
             ->from(Db_model::TABLE_PROJECT)
            ->join(Db_model::TABLE_USER, Db_model::TABLE_PROJECT.'.owner_id='.Db_model::TABLE_USER.'.id')
            ->where('owner_id', $owner_id)
            ->where(Db_model::TABLE_PROJECT. ".is_deleted", 0)
            ->get()->result_array();
    }


    /**
     * 获取项目成员
     * @param $pid
     * @return mixed
     */
    public function get_project_users($pid) {

        return $this->db->select(Db_model::TABLE_PROJECT_USER . ".*, ".Db_model::TABLE_USER . ".username")
            ->from(Db_model::TABLE_PROJECT_USER)
            ->join(Db_model::TABLE_USER, Db_model::TABLE_PROJECT_USER.'.uid='.Db_model::TABLE_USER.'.id')
            ->order_by(Db_model::TABLE_PROJECT_USER . ".createtime", "ASC")
            ->where(Db_model::TABLE_PROJECT_USER. ".pid", $pid)
            ->get()->result_array();
    }

    public function search_not_in_project_users($username, $pid) {
           $sql =  " select username, id from ".$this->getTable(Db_model::TABLE_USER).
               " where id not in (select uid from ".$this->getTable(Db_model::TABLE_PROJECT_USER) . " where pid=$pid) and username like '%".$username."%'";
          return $this->db->query($sql)->result_array();
    }

}